<?php

/*
 * gestiune tranzactii client-server
 */
require_once ('session.class.php');
require_once ('form.php');

class Process {

	private $sessionHandler;
	private $databaseHandler;

	/**
	 * constructor
	 */
	public function __construct($session, $currentDatabase){
		//public function __construct(& $session){
		$this->sessionHandler = $session;
		$this->databaseHandler =$currentDatabase;

		//logare
		if(isset($_POST['sublogin']))
		{
			$this->loginUser();
		}

		//creare cont nou
		elseif(isset($_POST['subjoin']))
		{
			$this->procRegisterUser();
		}

		//modificare date cont
		elseif(isset($_POST['subedit']))
		{
			$this->procEditAccount();
		}

		//generare parola noua
		elseif (isset($_POST['subforgot'])){
			$this->procForgotPass();
		}

		//creare proiect nou
		elseif (isset($_POST['subNewProj'])){
			$authors=$this->procNewProjFindFriends();
			//return true;
			//var_dump($_POST['mike']);
			//$authors=array('friend1','friend2','friend3','friend4');
			$this->procCreateNewProject($_POST['newProjDenumire'], $_POST['newProjType'], $authors);
			//var_dump($_POST['newProjAuths']);
		}

		//deschidere proiect
		elseif (isset($_POST['procOpenServDoc'])){
			//echo("sus");
			$this->openProject($_POST['procOpenServDoc']);
		}

		//afisare proiecte
		elseif ($_GET['center']== "openproj"){
			$this->setActiveProj();
		}

		//primire cereri ajax
		elseif (isset($_POST['procXHR'])){
			$this->handleXhrRequests();
			break;
		}

		//primire cereri ajax
		elseif (isset($_POST['procXHRComments'])){
			$this->handleXhrRequestsForComments();
			break;
		}

		//primire cereri ajax agenda
		elseif (isset($_POST['procXHRAgenda'])){
			$this->handleXhrRequestsForAgenda();
			break;
		}

		//logout
		elseif (isset($_GET['logout']) && $this->sessionHandler->logged_in){
			$this->procLogout();
			//$this->
		}
	}

	//  ----**** functii procesare date form-uri ****----

	//logare
	private function loginUser()
	{
		$form=new Form();
		//se incearca logarea
		$retval=$this->sessionHandler->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));

		//daca nu sunt erori userul este logat
		if ($retval)
		{
			header("Location: index.php");
		}
		//userul este trimis sa corecteze erorile
		else
		{
			$_SESSION['value_array']=$_POST;
			//$_SESSION['error_array']=$form->getErrorArray();
			header("Location: index.php?gcenter=login");
		}
	}

	//creare cont nou
	private function procRegisterUser()
	{
		//echo("inside");
		$form=new Form();

		//transforma username in litere mici daca este setat
		if (ALL_LOWERCASE)
		{
			$_POST['reguser']=strtolower($_POST['reguser']);
		}
		//echo $_POST['reguser']."<br />";
		//se incearca inregistrarea
		$retval=$this->sessionHandler->register($_POST['reguser'], $_POST['regpass'], $_POST['regemail']);
		//echo $retval;
		//succes
		if ($retval == 0)
		{
			$_SESSION['reguname']  =$_POST['reguser'];
			$_SESSION['regsuccess']=true;
			header("Location: index.php?gcenter=register");
		}
		//sunt erori la completarea formului
		else if ($retval == 1)
		{
			$_SESSION['value_array']=$_POST;
			//$_SESSION['error_array']=$form->getErrorArray();
			header("Location: index.php?gcenter=register");
		}
		//inregistrarea a esuat
		else if ($retval == 2)
		{
			$_SESSION['reguname']  =$_POST['reguser'];
			$_SESSION['regsuccess']=false;
			header("Location: index.php?gcenter=register");
		}
	}

	private function procForgotPass(){
		//procesare form schimbare parola: daca apar erori userul este redirectionat pentru a le corecta
		//global $database, $session, $mailer, $form;
		$form=new Form();
		$mailer=new Mailer();

		//verificare camp user din form
		$subuser=$_POST['usernewpass'];
		$field="usernewpass";

		if (!$subuser || strlen($subuser=trim($subuser)) == 0){
			$form->setError($field, "* Username not entered<br>");
		}else{
			//verifica daca user este in bd
			$subuser=stripslashes($subuser);

			if (strlen($subuser) < 5 || strlen($subuser) > 30 || !eregi("^([0-9a-z])+$", $subuser) || (!$this->databaseHandler->usernameTaken($subuser))){
				$form->setError($field, "* Username does not exist<br>");
			}
		}

		//daca sunt erori, redirectioneaza userul pentru a le corecta
		if ($form->num_errors > 0){
			$_SESSION['value_array']=$_POST;
			$_SESSION['error_array']=$form->getErrorArray();
		}else{//nu sunt erori: se genereaza parola noua si este este trimisa prin mail
			//genereaza parola noua
			$newpass=$this->sessionHandler->generateRandStr(8);

			//ia mailul userului
			$usrinf =$this->databaseHandler->getUserInfo($subuser);
			$email  =$usrinf['email'];

			//trimite mailul cu noua parola
			if ($mailer->sendNewPass($subuser, $email, $newpass)){
				//e-mail trimit-> update bd
				$this->databaseHandler->updateUserField($subuser, "password", md5($newpass));
				$_SESSION['forgotpass']=true;
			}else{//e-mailul nu a fost trimis-> nu mai modifica bd
				$_SESSION['forgotpass']=false;
			}
		}

		header("Location: index.php?gcenter=forgotpass");
	}

	//iesire cont
	private function procLogout()
	{
		$retval=$this->sessionHandler->logout();
		header("Location: index.php");
	}

	//modificare date cont
	private function procEditAccount()
	{
		global $session, $form;
		//incearca modificare date
		$retval=$session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email']);

		//succes
		if ($retval)
		{
			$_SESSION['useredit']=true;
			header("Location: index.php?comandaMijloc=updateAccount");
		}
		//erori la completare form, redirectioneaza user pt a le corecta
		else
		{
			$_SESSION['value_array']=$_POST;
			$_SESSION['error_array']=$form->getErrorArray();
			header("Location: index.php?comandaMijloc=updateAccount");
		}
	}

	/**
	 * creare proiect nou
	 */
	private function procCreateNewProject($name, $type='scientific', $authors){
		//echo("new proj creation");
		try {
			$this->createNewDocument($name);
			$this->createNewDocumentSettings($type, $authors);
		}catch (Exception $e){
			echo $e->getMessage();
		}

		header("Location: index.php?leftMenu=editor&center=view");
	}

	//creare document nou
	private function createNewDocument($name) {
		//creare fisier
		//echo("-----1----");
		$docPathTo = "..//dante/documente/" . $name;
		if (mkdir($docPathTo)) {
			try {
				$newDoc = new xmlDocument($name, $docPathTo);
			} catch (exception $e) {
				echo $e->getmessage() . "<br />";
			}
			//daca s'a creat cu succes, se inreg doc in bd
			try {
				//$this->sessionHandler->userid='123456';
				$this->databaseHandler->recordNewProject($name,$this->sessionHandler->userid);
				$this->sessionHandler->createNewDocument($name, $docPathTo);
			}catch (Exception $e){
				echo $e->getMessage();
			}
		} else {
			echo "NU s'a putut crea directorul!!!";
		}
	}

	//creare capitol nou
	private function createNewChapter($chapName, $chapId) {
		try {
			$newDoc = new xmlDocument($this->sessionHandler->docName, $this->sessionHandler->docPath);
			$newDoc->createNewChapter($chapName, $chapId);
		} catch (Exception $e) {
			echo $e->getMessage() . "<br />";
		}
	}

	/**
	 *creare setari document nou creat
	 */
	private function createNewDocumentSettings($type, $authors){
		$name=$_SESSION['docName'];
		$path=$_SESSION['docPath'];
		//echo $name."-".$path;

		try {
			$newDoc = new xmlDocument($name, $path);

			$docName=& $newDoc->docHandler->createElement('docName',$name);
			$newDoc->docInfoRoot->appendChild($docName);

			$docOwner=& $newDoc->docHandler->createElement('docOwner',$this->sessionHandler->username);
			$newDoc->docInfoRoot->appendChild($docOwner);

			$docCreationDate=& $newDoc->docHandler->createElement('docCreationDate',time());
			$newDoc->docInfoRoot->appendChild($docCreationDate);

			$docVersion=& $newDoc->docHandler->createElement('docVersion','1');
			$newDoc->docInfoRoot->appendChild($docVersion);

			$docLastUpdate=& $newDoc->docHandler->createElement('docLastUpdate',time());
			$newDoc->docInfoRoot->appendChild($docLastUpdate);

			$docType=& $newDoc->docHandler->createElement('docType', $type);
			$newDoc->docInfoRoot->appendChild($docType);

			$docState=& $newDoc->docHandler->createElement('docState','draft');
			$newDoc->docInfoRoot->appendChild($docState);

			$docAuthors=& $newDoc->docHandler->createElement('docAuthors');
			$docAuthors->appendChild($newDoc->docHandler->createElement('author', $this->sessionHandler->username));
			if($authors !== 0){
				foreach ($authors as $auths){
					$docAuthors->appendChild($newDoc->docHandler->createElement('author', $auths));
				}
			}
			$newDoc->docInfoRoot->appendChild($docAuthors);

			$newDoc->docHandler->save($newDoc->docPath);
		}catch (Exception $e){
			$e->getMessage();
		}
	}

	/**
	 * citeste settings.xml si cauta prietenii si verifica cine a fost ales sa participe
	 * @return Array $authors sau 0 daca nu s'a selectat nika
	 */
	private function procNewProjFindFriends(){
		$dom=new DOMDocument();
		$dom->load("xmlDb/agenda.xml");
		$xsl=new DOMDocument();
		$xsl->load("include/xsl/processListFriends.xsl");
		$proc=new XSLTProcessor();
		$proc->importStylesheet($xsl);
		$proc->setParameter("", "username", $_SESSION['username']);
		$friends=explode(";", $proc->transformToXml($dom));
		array_pop($friends);
		///var_dump($friends);
		$authors=array();
		foreach ($friends as $fr){
			if($_POST[$fr] !== NULL){
				$authors[]=$fr;
			}
		}
		//var_dump($authors);
		return $authors;
	}

	//gaseste proicte unui user
	private function setActiveProj(){
		///echo $this->sessionHandler->userid;
		$prj=$this->databaseHandler->getUserProjects($this->sessionHandler->username);
		if($prj){
			$this->sessionHandler->setActiveProjects($prj);
			//var_dump($prj);
		}
	}

	//activeaza un anumit proiect
	private function openProject($prj){
		$path = "..//dante/documente/" . $prj;
		$this->sessionHandler->createNewDocument($prj, $path);
		header("Location: index.php?leftMenu=editor&center=view&chapter=docInfo");
	}

	//tratare comenzi xhr
	private function handleXhrRequests(){
		//echo("inside");
		$command=$_POST['xhrCommand'];
		$chapter=$_POST['xhrCurrChap'];

		$elemType=$_POST['xhrElementType'];
		$elemId=$_POST['xhrId'];
		$elemValue=$_POST['xhrValue'];

		if($command == "newElement"){
			$docName=$_SESSION['docName'];
			$docPath=$_SESSION['docPath'];
			try {
				$loadChapter=new xmlChapter($chapter, rand(99,999999), $docPath);
				switch ($elemType){
					case "paragraf":
						$begin=microtime(true);
						$loadChapter->createNewParagraph($elemId, $elemValue);
						$end=microtime(true);
						$totalTime=$end-$begin;
						echo("Command executed in ".$totalTime." seconds");
						break;

					case "note":
						$loadChapter->createNewNote($elemId, $elemValue);
						echo("OK");
						break;

					case "table":
						$argumets=$this->deserializeXhr($elemValue);
						$loadChapter->createNewTable($elemId, 0, $argumets[0][1], $argumets[1][1]);
						echo "OK";
						break;
				}
			}catch (Exception $e){
				echo $e->getMessage();
			}
		}

		if ($command == "updateElement"){
			$docName=$_SESSION['docName'];
			$docPath=$_SESSION['docPath'];
			try {
				$loadChapter=new xmlChapter($chapter, rand(99,999999), $docPath);
				switch ($elemType){
					case "paragraph":
						$loadChapter->updateParagraph($elemId, $elemValue);
						echo("OK");
						break;

					case "note":
						return 1;
						break;
				}
			}catch (Exception $e){
				echo $e->getMessage();
			}
		}
	}

	//tratare xhr editor comentarii
	private function handleXhrRequestsForComments(){
		//echo("inside");
		$chapterId=$_POST['xhrCurrChapId'];
		$command=$_POST['xhrCommand'];

		$cmtId=$_POST['xhrCmtId'];
		$author=$_POST['xhrAuthor'];
		$elemId=$_POST['xhrElemId'];
		$date=$_POST['xhrDate'];
		$content=$_POST['xhrContent'];

		$docPath=$_SESSION['docPath'];

		try {
			$loadChapterComments=new xmlChapterComment($chapterId, $docPath);
			switch ($command){
				case "new":
					$loadChapterComments->createNewComment($cmtId, $author, $elemId, $date, $content);
					echo("OK");
					break;

				case "update":
					$loadChapterComments->updateComment($cmtId, $author, $elemId, $date, $content);
					echo("OK");
					break;
			}
		}catch (Exception $e){
			echo $e->getMessage();
		}
	}

	private function handleXhrRequestsForAgenda(){
		$friend=$_POST['friend'];
		
		$dom=new DOMDocument();
		$dom->load("xmlDb/agenda.xml");
		$xsl=new DOMDocument();
		$xsl->load("include/xsl/agendaHCard.xsl");
		$proc=new XSLTProcessor();
		$proc->importStylesheet($xsl);
		$proc->setParameter("", "username", $friend);
		$return=$proc->transformToXml($dom);
		if($return){
			echo $return;
			return true;
		}else{
			echo("user not defined!!!");
			return false;
		}
	}

	private function deserializeXhr($string){
		$temp=explode(";",$string);
		$temp2=array();
		$final=array();

		for ($i=0; $i<count($temp); $i++){
			$var=explode(":",$temp[$i]);
			$temp2[$i][0]=$var[0];
			$temp2[$i][1]=$var[1];
		}

		for ($i=0; $i<count($temp2); $i++){
			$var=explode(",",$temp2[$i][1]);
			if(count($var) > 1){
				$final[$i][0]=$temp2[$i][0];
				$final[$i][1]=array();
				for ($j=0; $j < count($var); $j++){
					$final[$i][1][$j]=$var[$j];
				}
			}else {
				$final[$i][0]=$temp2[$i][0];
				$final[$i][1]=$temp2[$i][1];
			}
		}

		return $final;
	}

}
?>